<?php
/**
 * Created by PhpStorm
 * User: allen.qiang
 * Date: 14-12-29
 * Time: 下午 14:00
 */
quanli_require('module/base/activity/activityConfig.class.php');

class activityBank {

    /**
     * 得到银行五折购活动的信息
     * $arg_array 用户信息
     * $activity_name 活动配置名称
     * @return $activity_array
     * @author  20141229 allen.qiang <allen.qiang@fistforward.com>
     */
    public function activity_master(&$arg_array,$activity_name){
        global $G_SHOP;

        //实例化配置类
        $activity_config = new activityConfig($activity_name); //银行五折购活动配置
        $config_array = $activity_config->config;

        $isbool=false;
        //sql字符串
        $sql = ' ';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        //会员名
        if (isset($arg_array['custID']) && is_numeric($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['custID']);
            $isbool=true;
        }

        //会员ID
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['pcustID'];
            $isbool=true;
        }
        //促销渠道ID
        if (isset($config_array['billPromotion']) && !empty($config_array['billPromotion'])) {
            $sql .= ' AND billPromotion=?';
            $params_type .= 's';
            $params_array[] = $config_array['billPromotion'];
        }
        //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<得到银行五折购使用状态 0：未使用，1：已使用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        $status=0;
       if($isbool){
           $sql_master="SELECT COUNT(1) AS item_count FROM `bill_master` WHERE bill_status<>10 AND createTime>'".date('Y-m-d 00:00:00')."' AND createTime<'".date('Y-m-d 23:59:59')."' ".$sql;
           $temp_item_master = &$G_SHOP->DBCA->stmt_query($sql_master,$params_type,$params_array);
           $item_count = $temp_item_master[0]->item_count;
           if($item_count>0){ //已使用
               $status=1;
           }
       }

        //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<得到活动的每日蛋糕数量>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        $sql_master2="SELECT COUNT(1) AS item_count FROM `bill_master` WHERE bill_status<>10 AND createTime>'".date('Y-m-d 00:00:00')."' AND createTime<'".date('Y-m-d 23:59:59')."' AND billPromotion=".$config_array['billPromotion'];
        $temp_item_master2 = &$G_SHOP->DBCA->stmt_query($sql_master2);
        $sql_master3="SELECT COUNT(1) AS item_count FROM `bill_master` WHERE bill_status<>10 AND createTime>'".date('Y-m-d 00:00:00',strtotime('-1 day'))."' AND createTime<'".date('Y-m-d 23:59:59',strtotime('-1 day'))."' AND billPromotion=".$config_array['billPromotion'];
        $temp_item_master3 = &$G_SHOP->DBCA->stmt_query($sql_master3);
        $number=$config_array['cake_sum'];
        if($temp_item_master3[0]->item_count>$number){
            $number =$number- ($temp_item_master3[0]->item_count-$number);
        }
        if($temp_item_master2){
            $number =$number- $temp_item_master2[0]->item_count;
        }
        if($number<0)
            $number=0;

        //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<是否在活动时间内 0：未在活动时间内；1：在活动时间内>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        $isDate=0;
        if(strstr($config_array["activity_Week"],date('w')) && date('Y-m-d H:i:s')>=$config_array["startTime"] && date('Y-m-d H:i:s')<=$config_array["endTime"] && date('Y-m-d H:i:s')>=(date('Y-m-d').' '.$config_array["startPeriod"]) && date('Y-m-d H:i:s')<=(date('Y-m-d').' '.$config_array["endPeriod"])){
            $isDate=1;
        }

        //活动信息数组
        $activity_array = array(
            'billPromotion' => $config_array['billPromotion'], //促销渠道ID
            'activity_status'	     => $status, //使用状态
            'startTime'	     => $config_array['startTime'], //活动开始时间
            'endTime'	     => $config_array['endTime'], //活动结束时间
            'cityID'	     => $config_array['cityID'], //活动城市ID
            'activity_num' => $number, //每日蛋糕所剩数量
            'isDate'        => $isDate, //是否在活动时间内
            'send_end_time' => $config_array["send_end_time"], //配送结束时间
            'activity_Week' => $config_array["activity_Week"], //活动的订购星期
            'startPeriod' => $config_array["startPeriod"], //活动当天时间段起始时间
            'endPeriod' => $config_array["endPeriod"], //活动当天时间段结束时间
            'paymentID' =>$config_array["paymentID"] //银行付款方式ID
        );

        return $activity_array;

    }

    /**
     * 活动银行信息收集
     * $sku 银行记录的名称
     * @author  20141229 allen.qiang <allen.qiang@fistforward.com>
     */
    public function bank_log($sku){
        global $G_SHOP;

        try {
            $G_SHOP->DBCA->beginTransaction();

            $activityLog = new entity('activity_log');
            $activityLog->creator = $G_SHOP->currentCustomerID==""?$this->getIP():$G_SHOP->currentCustomerID;
            $activityLog->pcustID = $G_SHOP->currentPCustID;
            $activityLog->sku = $sku;

            $G_SHOP->DBCA->save($activityLog) ;
            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '记录成功' );
        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 查询IP
     * @return $realip
     * @author  20141219 allen.qiang <allen.qiang@fistforward.com>
     */
    public function getIP()
    {
        static $realip;
        if (isset($_SERVER)){
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")){
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }

    /**
     * 添加带来源标记的会员信息
     * @author  20150108 allen.qiang <allen.qiang@fistforward.com>
     */
    public function register() {

        global $G_SHOP;

        if (!isset($_REQUEST['custSource']) || !in_array($_REQUEST['custSource'], array(1, 2, 4))) {
            $_REQUEST['custSource'] = 1;
        }

        //检查短信验证码
        $sms_ysm = $G_SHOP->sessionCache_get('sms_yzm_' . $_REQUEST['regName']);

        if (is_null($sms_ysm)) {
            returnJsonData('短信验证码已失效', 400);
        } elseif ($sms_ysm != md5($_REQUEST['smsyzm'])) {
            returnJsonData('短信验证码有误');
        }

        $G_SHOP->sessionCache_remove( 'sms_yzm_' . $_REQUEST['regName'] );
        $G_SHOP->sessionCache_remove( 'sms_yzm__time_' . $_REQUEST['regName'] );

        /**
         * =============================
         * 前台注册会员信息
         * =============================
         */

        //实例会员类
        quanli_require('module/base/customer/quanliCust.class.php');
        $quanliCust = new quanliCust();

        //前台注册会员信息
        $args_array = array(
            'custID' => $_REQUEST['regName'],
            'pwd' => $_REQUEST['regPwd'],
            'pwd2' => $_REQUEST['regPwd2'],
            'custSource' => $_REQUEST['custSource'],
            'custType' => 1,
            'custSource_ext' => $_REQUEST['cust_source_mark']  //会员来源扩展

        );
        $result_array = $this->registerAdd( $args_array );
        if ($result_array['code'] != 200) {
            returnJsonData($result_array['message'], $result_array['code']);
        }
        /**
         * =============================
         * 前台注册会员信息
         * =============================
         */


        /**
         * =============================
         * 更新会员登录信息
         * =============================
         */
        $quanliCust->shopCheckin( $result_array['data'] );
        /**
         * =============================
         * 更新会员登录信息
         * =============================
         */


        /**
         * ==========================
         * 渠道会员
         * ==========================
         */
        $tracker_code = $G_SHOP->get_cookie_info('__etrack_tracker_code');
        $key1 = $G_SHOP->get_cookie_info('__etrack_key1');
        $key2 = $G_SHOP->get_cookie_info('__etrack_key2');
        $key3 = $G_SHOP->get_cookie_info('__etrack_key3');
        $referrer = $G_SHOP->get_cookie_info('__etrack_referrer');
        $referrer_time = $G_SHOP->get_cookie_info('__etrack_referrer_time');
        $tracker = $G_SHOP->get_cookie_info('__etrack');
        $tracker_array = explode('|', $tracker);
        $etrack_switch = $G_SHOP->get_cookie_info('__etrack_switch');

        $cityName = '';
        $city_id = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        if($city_id !== null){
            //获取城市名称
            $citySql = 'SELECT name FROM sys_region WHERE id = ' . intval($city_id);
            $cityRow = $G_SHOP->DBCA->stmt_query($citySql);
            $cityName = !empty($cityRow)?$cityRow[0]->name:'';
        }

        $cust_channel = new entity('cust_channel');
        $cust_channel->pcustID = $result_array['data']['pcustID'];
        if (!$G_SHOP->DBCA->fetch($cust_channel)) {
            $cust_channel->creator = 'system';
            $cust_channel->source_url = $referrer;
            $cust_channel->source_time = $referrer_time;
            $cust_channel->key1 = $key1;
            $cust_channel->key2 = $key2;
            $cust_channel->key3 = $key3;
            $cust_channel->tracker_code = $tracker_code;
            $cust_channel->session_id = $tracker_array[0];
            $cust_channel->switch_id = $etrack_switch;
            $cust_channel->ip = get_ip();
            $cust_channel->source_channel = $_REQUEST['custSource'] == 1 ? 'web' : 'wap';
            $cust_channel->city_name = $cityName;
            $G_SHOP->DBCA->save( $cust_channel );
        }
        /**
         * ==========================
         * 渠道会员
         * ==========================
         */


        returnJsonData('ok', 200, $result_array['data']['custID']);

    }

    /**
     * 注册会员
     * @param $arg_array
     * @return array
     */
    public function registerAdd( $arg_array ) {

        global $G_SHOP;

        //加载类文件
        quanli_include('module/base/customer/custRank.class.php');

        //实例会员等级类
        $custRank = new custRank();

        //检查参数
        if (!isset($arg_array['custID'], $arg_array['pwd'], $arg_array['custType'], $arg_array['custSource'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!in_array($arg_array['custType'], array(1, 2, 3))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!in_array($arg_array['custSource'], array(1, 2, 3, 4, 5, 6, 7))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if ($arg_array['custSource'] != 7) {
            if (!is_mobile($arg_array['custID'])) {
                return array( 'code' => 400, 'message' => '请输入手机号码' );
            }
        }

        if (!is_pwd($arg_array['pwd'])) {
            return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字' );
        }

        if ($arg_array['custSource'] == 7) {
            $custID = $arg_array['custID'];
            $mobile = '';
        } else {
            $custID = $mobile = $arg_array['custID'];
        }

        $pwd = $arg_array['pwd'];

        //第三方登录会员名
        $unionName = isset($arg_array['unionName']) ? trim($arg_array['unionName']) : null;

        //会员昵称
        $nickName = isset($arg_array['nickName']) ? trim($arg_array['nickName']) : $custID;

        //推荐人客户号
        $recom_pcustID = isset($arg_array['referrer']) && is_numeric($arg_array['referrer']) ? $arg_array['referrer'] : null;

        //会员类型
        $custType = $arg_array['custType'];

        //会员来源
        $custSource = $arg_array['custSource'];

        //会员来源扩展
        $custSource_ext=$arg_array["custSource_ext"];

        try {

            //查询初始会员等级
            $rank_array = $custRank->getRankForNeedAmt( 0 );
            if (!$rank_array) {
                throw new Exception('会员数据未初始化', 404);
            }

            //检查会员并保存
            $cust_obj = new entity('cust_master');
            $cust_obj->custID = $custID;
            if ($G_SHOP->DBCA->fetch($cust_obj)) {
                throw new Exception('会员名已被使用，请使用其他会员名尝试注册', 404);
            }
            $cust_obj->creator = $custID;
            $cust_obj->pcustID = generate_seqno('seqno_customer');
            $cust_obj->nickName = $custID;
            $cust_obj->rankID = $rank_array['rankID'];
            $cust_obj->rankName = $rank_array['rankName'];
            $cust_obj->pwd = md5($pwd);
            $cust_obj->useFlg = 1;
            $cust_obj->head_pic = 'default_user.gif';
            $cust_obj->unionName = $unionName;
            $cust_obj->nickName = $nickName;
            $cust_obj->mobile = encryptD($mobile);
            $cust_obj->recom_pcustID = $recom_pcustID;
            $cust_obj->sumAmt = 0;
            $cust_obj->custSource = $custSource;
            $cust_obj->custType = $custType;
            $cust_obj->custSource_ext =$custSource_ext ;
            if (!$G_SHOP->DBCA->save($cust_obj)) {
                throw new Exception('页面已过期，请刷新页面重试', 404);
            }

            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            //加载会员促销类
            quanli_include('module/base/promotion/promotionCustomer.class.php');


            //实例会员促销类
            $promotionHandler = new promotionCustomer();


            //查询会员促销活动并发放
            $promotionHandler->grantCustPromotion( $cust_obj->pcustID, $custID, 1 );


            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            $result_array = array(
                'pcustID' => $cust_obj->pcustID,
                'custID' => $custID,
                'nickName' => $nickName,
                'email' => null,
                'custType' => $custType,
                'mobile' => $mobile,
                'recom_pcustID' => $recom_pcustID
            );

            return array( 'code' => 200, 'message' => 'ok', 'data' => $result_array );

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }
} 